package com.distribute.core.notify.redis.redisTemplate;

import cn.hutool.core.util.StrUtil;
import com.distribute.common.Constants;
import com.distribute.common.NotifyPluginType;
import com.distribute.core.annotation.DLCCell;
import com.distribute.core.constants.CacheConstants;
import com.distribute.core.constants.LocalCacheConstants;
import com.distribute.core.init.AbstractNotifyComponent;
import com.distribute.core.notify.DLCNotify;
import com.distribute.core.notify.redis.DLCRedisCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * redis 通知组件 初始化
 * 初始化 channel
 *
 * @author chennengcheng
 * @date 2021-09-17 17:19
 * @remark
 */

public class RedisTemplateNotifyComponent extends AbstractNotifyComponent {

    private static final Logger log = LoggerFactory.getLogger(RedisTemplateNotifyComponent.class);


    @Override
    public void init() {
        // 设置插件类型为 redis
        LocalCacheConstants.setNotifyPluginType(NotifyPluginType.REDIS);
    }

    @Bean
    public RedisMessageListenerContainer container(DLCRedisCenter<RedisTemplate> dlcRedisCenter) {
        RedisTemplate redisClient = dlcRedisCenter.getRedisClient();
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        log.info("初始化 listener");
        container.setConnectionFactory(Objects.requireNonNull(redisClient.getConnectionFactory()));
        // 将 mode_prefix 做 topic
        CacheConstants.CELLS_MAP.keySet().forEach(className -> {
            DLCCell dlcCell = CacheConstants.CELLS_MAP.get(className);
            String modelPrefix = dlcCell.modelPrefix();
            String model = dlcCell.model();
            String topicName = Constants.DLC_CACHE + StrUtil.COLON + modelPrefix + StrUtil.COLON + model;
            log.info("RedisTemplate 正在初始化 redis 订阅 topicChannel： " + topicName);
            container.addMessageListener(new RedisTemplateNotifyMessageListener(), new ChannelTopic(topicName));
        });

        return container;
    }

    @Bean
    public DLCNotify notifyCacheUpdateImpl(DLCRedisCenter<RedisTemplate> dlcRedisCenter){
        RedisTemplate redisTemplate = dlcRedisCenter.getRedisClient();
        return new RedisTemplateTopicNotifyImpl(redisTemplate);
    }
}
